# Create your views here.

from django.http import HttpResponse, Http404
from django.shortcuts import render, redirect, get_object_or_404
from django.core.paginator import Paginator, EmptyPage, PageNotAnInteger
from django.contrib.auth.decorators import login_required
from django.utils import simplejson
from django.views.decorators.csrf import csrf_exempt
from django.contrib.sites.models import Site
from .models import Article, Comment
from .forms import ImageUploadForm
from .manager import setUserImage
from confs import SmartConf, getSubTypeList, isValidTypeId
import smartform, copy
import os

ARTICLE_NUM_OF_PAGE = 10

def index(request, type1, template):
    return render(request, template, {'forum_config':getSubTypeList(int(type1))})


def article_list(request, typeid, page, bigtype, template):
    typeid = int(typeid)
    page = int(page)

    if typeid == 0:
        article_list = Article.objects.filter(bigtype=bigtype)
    else:
        article_list = Article.objects.filter(bigtype=bigtype, typeid=typeid)

    paginator = Paginator(article_list, ARTICLE_NUM_OF_PAGE)

    try:
        articles = paginator.page(page)
    except EmptyPage:
        articles = paginator.page(paginator.num_pages)

    for a in articles:
        a.typename = SmartConf[a.typeid]["name"] 

    return render(request, template, {'article_list': articles, 'page':paginator, 'bigtype':bigtype, 'typeid':typeid})


def article_detail(request, articleid, template):
    article = get_object_or_404(Article, pk=articleid)
    article.reads = article.reads + 1
    article.save()
    article.typename = SmartConf[article.typeid]["name"]
    return render(request, template, {"article": article, 'forum_config':SmartConf}) 

def showtypes(request, bigtype, template):
    if request.method == 'GET':
        return render(request, template, {'curtype': SmartConf[bigtype], 'subtypes':getSubTypeList(bigtype)}) 
    else:
        raise Http404()

def add_article(request, typeid, template):
    typeid = int(typeid)
    if not isValidTypeId(typeid):
        raise Http404()

    form = ImageUploadForm()
    conf = smartform.getconf(typeid)
    if request.method == 'GET':
        return render(request, template, {'form':form, 'fields':conf['fields'], 'typeobj':SmartConf[typeid]})

    else:
        print dir(request.POST)
        print request.POST
        conf = smartform.getconf(typeid)
        ret, cleaned_data = smartform.validate(request.POST, conf)
        if ret:
            article = Article() 
            article.typeid = typeid 
            article.bigtype = typeid/100 
            article.author = request.user
            article.title = cleaned_data["title"]["value"]
            article.content= cleaned_data["content"]["value"]
            article.exdata = smartform.encode(cleaned_data)
            site = get_object_or_404(Site, pk=1)
            article.site = site
            article.save()
            
            for imgname in request.POST.getlist('userimg', []):
                setUserImage(request.user, imgname, article)

            return redirect("/forum/detail/%s/"%(article.id))
        else:
            fields = copy.deepcopy(conf["fields"])
            for v in fields:
                n = v["name"]
                if cleaned_data.has_key(n):
                    v["value"] = cleaned_data[n].get("value", "")
                    v["error"] = cleaned_data[n].get("error", "")

            return render(request, template, {'typeobj':SmartConf[typeid], 'fields':fields})


def search_article(request):
    return HttpResponse("search_article")


def edit_article(request):
    return HttpResponse("edit_article")

@csrf_exempt
def add_comment(request, articleid):
    if request.method != 'POST': 
        raise Http404()

    content = request.POST.get('content', '') 
    if len(content) == 0:
        raise Http404()

    article = get_object_or_404(Article, pk=articleid)
    json = {}
    c = Comment()
    c.article = article
    c.author = request.user
    c.content = content
    c.save()
    json['ret'] = True
    json['author'] = request.user.username
    json['content'] = content
    json['posttime'] = c.posttime.strftime("%Y-%m-%d %H:%M:%S") 
    article.comments = article.comments + 1
    article.save()

    return HttpResponse(simplejson.dumps(json))


from .models import SupportArt, SUPPORT_ZAN, SUPPORT_SAVE
def support_article(request, articleid, optype):
    if optype not in (SUPPORT_ZAN, SUPPORT_SAVE):
        raise Http404()

    article = get_object_or_404(Article, pk=articleid)
    json_ret = {}
    qs = SupportArt.objects.filter(user=request.user, article_id=articleid, tag=optype)
    if len(qs)!= 0:
        json_ret['ret'] = 'fail' 
        json_ret['err'] = 'duplicated operation'
        return HttpResponse(simplejson.dumps(json_ret))

    support = SupportArt()
    support.user = request.user
    support.article = article
    support.tag = optype
    support.save()

    if optype == SUPPORT_ZAN: article.zans = article.zans + 1
    if optype == SUPPORT_SAVE: article.saves = article.saves+ 1
    article.save()

    json_ret['ret'] = 'ok' 
    return HttpResponse(simplejson.dumps(json_ret))


def imgupload(request):
    if request.method == 'GET':
        f = ImageUploadForm()
        return render(request, "upload.html", {"form":f})
    else:
        f = ImageUploadForm(request.POST, request.FILES)
        if f.is_valid():
            img = f.save(False)
            img.user = request.user
            img.width = img.image.width
            img.height = img.image.height
            img.size = img.image.size
            img.save()
            img.path = img.image.name
            img.save()

            imgurl = "/static/%s/" % (img.image.name)
            return render(request, "upload_iframe.html", {"imgurl":imgurl, "imgname":img.image.name})

        return render(request, "upload.html", {"form":f})


